// ==UserScript==
// @name         网页图标获取器增强版
// @namespace    http://tampermonkey.net/
// @version      0.3.3
// @description  获取当前网页的所有图标并提供下载(按Alt+F键激活)，支持更多特殊图标格式，深色主题更护眼
// @author       Cursor
// @match        *://*/*
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @grant        GM_registerMenuCommand
// @grant        GM_xmlhttpRequest
// @connect      *
// @icon     https://gitee.com/selling-surprises/Greasyfork-Script-repository/raw/main/%E5%AE%9E%E7%94%A8%E8%84%9A%E6%9C%AC/%E7%BD%91%E9%A1%B5%E5%9B%BE%E6%A0%87%E8%8E%B7%E5%8F%96%E5%99%A8/Web-icon.png
// ==/UserScript==

/*
更新日志:
v0.3.3 - 修复base64编码图标无法在浏览器窗口打开的问题
v0.3.2 - 添加深色主题，优化界面显示效果
v0.3.1 - 增强对比度，改善背景色
v0.3.0 - 初始增强版本，支持更多图标格式
*/

(function() {
    'use strict';

    // 增强版样式：改善对比度和可见性 - 深色主题
    GM_addStyle(`
        #favicon-grabber {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #2c3e50;
            color: #ffffff;
            border: 1px solid #4a6b8c;
            border-radius: 5px;
            padding: 10px;
            z-index: 9999;
            box-shadow: 0 0 15px rgba(0,0,0,0.6);
            max-width: 300px;
            max-height: 500px;
            overflow-y: auto;
            display: none;
            font-family: Arial, sans-serif;
            transition: all 0.3s ease;
        }
        #favicon-grabber::-webkit-scrollbar {
            width: 8px;
        }
        #favicon-grabber::-webkit-scrollbar-track {
            background: #1a2a3a;
            border-radius: 5px;
        }
        #favicon-grabber::-webkit-scrollbar-thumb {
            background: #4a6b8c;
            border-radius: 5px;
        }
        #favicon-grabber::-webkit-scrollbar-thumb:hover {
            background: #5c7d9e;
        }
        #favicon-grabber h3 {
            margin-top: 0;
            margin-bottom: 10px;
            font-size: 16px;
            color: #ecf0f1;
        }
        .favicon-item {
            margin-bottom: 10px;
            border-bottom: 1px solid #4a6b8c;
            padding-bottom: 10px;
            background: #34495e;
            padding: 8px;
            border-radius: 4px;
            transition: background 0.2s ease;
        }
        .favicon-item:hover {
            background: #3d5a76;
        }
        .favicon-item img {
            max-width: 32px;
            max-height: 32px;
            margin-right: 10px;
            vertical-align: middle;
            border: 1px solid #7f8c8d;
            background: #fff;
            border-radius: 4px;
            padding: 2px;
            transition: transform 0.2s ease;
        }
        .favicon-item img:hover {
            transform: scale(1.1);
        }
        .favicon-url {
            font-size: 12px;
            word-break: break-all;
            margin: 5px 0;
            color: #bdc3c7;
            background: #243342;
            padding: 4px;
            border-radius: 3px;
        }
        .favicon-actions {
            margin-top: 5px;
            display: flex;
            justify-content: space-between;
        }
        .favicon-actions button {
            flex: 1;
            margin-right: 5px;
            font-size: 12px;
            padding: 4px 8px;
            cursor: pointer;
            background: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            transition: background 0.2s ease;
        }
        .favicon-actions button:last-child {
            margin-right: 0;
        }
        .favicon-actions button:hover {
            background: #2980b9;
        }
        .close-button {
            position: absolute;
            top: 5px;
            right: 5px;
            cursor: pointer;
            font-size: 16px;
            color: #ecf0f1;
            background: none;
            border: none;
            transition: color 0.2s ease;
        }
        .close-button:hover {
            color: #e74c3c;
        }
        .reload-button {
            position: absolute;
            top: 5px;
            right: 30px;
            cursor: pointer;
            font-size: 14px;
            color: #ecf0f1;
            background: none;
            border: none;
            padding: 0;
            transition: color 0.2s ease, transform 0.3s ease;
        }
        .reload-button:hover {
            color: #3498db;
            transform: rotate(180deg);
        }
        .format-filter {
            margin-bottom: 10px;
            font-size: 12px;
            display: flex;
            flex-direction: column;
            gap: 5px;
            background: #34495e;
            padding: 6px;
            border-radius: 4px;
        }
        .format-filter span {
            color: #ecf0f1;
            font-weight: bold;
            margin-right: 5px;
        }
        .format-filter label {
            margin-right: 8px;
            cursor: pointer;
            color: #bdc3c7;
            background: #243342;
            padding: 2px 4px;
            border-radius: 3px;
            display: inline-block;
            transition: background 0.2s ease;
        }
        .format-filter label:hover {
            background: #2c3e50;
        }
        .format-filter input[type="checkbox"] {
            vertical-align: middle;
            margin-right: 3px;
        }
        .status-text {
            font-size: 12px;
            color: #2ecc71;
            margin-bottom: 5px;
            background: #243342;
            padding: 4px;
            border-radius: 3px;
            text-align: center;
        }
        .version-info {
            font-size: 10px;
            color: #7f8c8d;
            text-align: right;
            margin-top: 5px;
            padding-top: 5px;
            border-top: 1px dashed #4a6b8c;
        }
    `);

    let panel = null;
    let icons = [];
    
    // 脚本版本
    const scriptVersion = '0.3.3';
    
    // 增强版：支持更多图标格式
    let formatFilters = {
        'ico': true,
        'png': true,
        'jpg': true,
        'jpeg': true, 
        'svg': true,
        'webp': true,
        'gif': true,
        'bmp': true,
        'avif': true,
        'tiff': true,   // 新增
        'tif': true,    // 新增
        'heic': true,   // 新增
        'heif': true,   // 新增
        'jxr': true,    // 新增
        'jp2': true,    // 新增(JPEG 2000)
        'apng': true,   // 新增(动画PNG)
        'jfif': true,   // 新增
        'base64': true, // 新增
        'other': true
    };

    // 注册菜单命令
    GM_registerMenuCommand('获取网页图标(深色增强版)', togglePanel);

    // 注册快捷键 Alt+F
    document.addEventListener('keydown', function(e) {
        if (e.altKey && e.key === 'f') {
            togglePanel();
        }
    });

    function togglePanel() {
        if (panel) {
            panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
        } else {
            createPanel();
            panel.style.display = 'block';
        }
    }

    function createPanel() {
        // 创建图标面板
        panel = document.createElement('div');
        panel.id = 'favicon-grabber';
        
        // 添加关闭按钮
        const closeButton = document.createElement('span');
        closeButton.className = 'close-button';
        closeButton.innerHTML = '×';
        closeButton.addEventListener('click', function() {
            panel.style.display = 'none';
        });
        
        // 添加刷新按钮
        const reloadButton = document.createElement('button');
        reloadButton.className = 'reload-button';
        reloadButton.innerHTML = '↻';
        reloadButton.title = '重新获取图标';
        reloadButton.addEventListener('click', function() {
            icons = [];
            getAllIcons();
        });
        
        // 添加标题
        const title = document.createElement('h3');
        title.textContent = `网页图标获取器(深色版 v${scriptVersion})`;
        title.style.textAlign = 'center';
        title.style.backgroundColor = '#1a2a3a';
        title.style.padding = '5px 0';
        title.style.borderRadius = '3px';
        title.style.marginBottom = '15px';
        
        // 添加状态文本
        const statusText = document.createElement('div');
        statusText.className = 'status-text';
        statusText.textContent = '正在搜索图标...';
        
        // 添加格式过滤器
        const formatFilterContainer = document.createElement('div');
        formatFilterContainer.className = 'format-filter';
        
        // 添加过滤器标题
        const filterTitle = document.createElement('span');
        filterTitle.textContent = '格式过滤: ';
        formatFilterContainer.appendChild(filterTitle);
        
        // 创建两行过滤器布局
        const row1 = document.createElement('div');
        row1.style.display = 'flex';
        row1.style.flexWrap = 'wrap';
        row1.style.marginBottom = '5px';
        
        const row2 = document.createElement('div');
        row2.style.display = 'flex';
        row2.style.flexWrap = 'wrap';
        
        let counter = 0;
        
        for (const format in formatFilters) {
            const label = document.createElement('label');
            const checkbox = document.createElement('input');
            checkbox.type = 'checkbox';
            checkbox.checked = formatFilters[format];
            checkbox.dataset.format = format;
            checkbox.addEventListener('change', function() {
                formatFilters[this.dataset.format] = this.checked;
                updateIconsDisplay();
            });
            
            label.appendChild(checkbox);
            label.appendChild(document.createTextNode(format === 'other' ? '其他' : format));
            
            // 将格式分成两行显示，更易读
            if (counter < Object.keys(formatFilters).length / 2) {
                row1.appendChild(label);
            } else {
                row2.appendChild(label);
            }
            counter++;
        }
        
        formatFilterContainer.appendChild(row1);
        formatFilterContainer.appendChild(row2);
        
        panel.appendChild(closeButton);
        panel.appendChild(reloadButton);
        panel.appendChild(title);
        panel.appendChild(statusText);
        panel.appendChild(formatFilterContainer);
        
        // 添加版本信息
        const versionInfo = document.createElement('div');
        versionInfo.className = 'version-info';
        versionInfo.textContent = `深色主题版本 v${scriptVersion}`;
        panel.appendChild(versionInfo);
        
        // 获取所有图标
        getAllIcons(statusText);
        
        document.body.appendChild(panel);
    }
    
    function getAllIcons(statusElement) {
        // 清空图标数组
        icons = [];
        
        // 获取所有可能的图标
        
        // 1. 查找链接标签中的图标
        const linkElements = document.querySelectorAll('link[rel*="icon"], link[rel="shortcut icon"], link[rel="apple-touch-icon"], link[rel="apple-touch-icon-precomposed"]');
        linkElements.forEach(function(link) {
            const href = link.href;
            if (href) {
                addIconIfNotExists({
                    url: href,
                    type: link.getAttribute('rel') || '未知',
                    size: link.getAttribute('sizes') || '未知',
                    source: 'link标签'
                });
            }
        });

        // 新增：查找内联的Base64编码图标
        const baseElements = document.querySelectorAll('link[rel*="icon"][href^="data:"], link[rel="shortcut icon"][href^="data:"]');
        baseElements.forEach(function(link) {
            const href = link.href;
            if (href && href.startsWith('data:')) {
                addIconIfNotExists({
                    url: href,
                    type: link.getAttribute('rel') || '内联图标',
                    size: link.getAttribute('sizes') || '未知',
                    source: 'Base64内联',
                    format: 'base64'
                });
            }
        });

        // 2. 查找网站的manifest.json中的图标
        const manifestLink = document.querySelector('link[rel="manifest"]');
        if (manifestLink && manifestLink.href) {
            if (statusElement) statusElement.textContent = '正在从manifest.json获取图标...';
            fetch(manifestLink.href)
                .then(response => response.json())
                .then(data => {
                    if (data.icons && Array.isArray(data.icons)) {
                        data.icons.forEach(icon => {
                            if (icon.src) {
                                const iconUrl = new URL(icon.src, window.location.origin).href;
                                addIconIfNotExists({
                                    url: iconUrl,
                                    type: 'manifest icon',
                                    size: icon.sizes || '未知',
                                    source: 'manifest.json'
                                });
                            }
                        });
                        updateIconsDisplay();
                    }
                })
                .catch(() => {
                    // 忽略错误
                })
                .finally(() => {
                    if (statusElement) statusElement.textContent = '图标搜索完成';
                });
        }
        
        // 3. 搜索网站根目录下常见的图标文件
        const rootUrl = window.location.origin;
        // 增强版：添加更多可能的图标路径
        const commonIcons = [
            '/favicon.ico',
            '/favicon.png',
            '/favicon.jpg', 
            '/favicon.svg',
            '/favicon.webp',
            '/favicon.gif',
            '/favicon-16x16.png',
            '/favicon-32x32.png',
            '/favicon-96x96.png',
            '/favicon-192x192.png',
            '/apple-touch-icon.png',
            '/apple-touch-icon.jpg',
            '/apple-touch-icon-precomposed.png',
            '/apple-touch-icon-57x57.png',
            '/apple-touch-icon-60x60.png',
            '/apple-touch-icon-72x72.png',
            '/apple-touch-icon-76x76.png',
            '/apple-touch-icon-114x114.png',
            '/apple-touch-icon-120x120.png',
            '/apple-touch-icon-144x144.png',
            '/apple-touch-icon-152x152.png',
            '/apple-touch-icon-180x180.png',
            '/touch-icon-iphone.png',
            '/touch-icon-ipad.png',
            '/touch-icon-iphone-retina.png',
            '/touch-icon-ipad-retina.png',
            '/logo.png',
            '/logo.svg',
            '/icon.png',
            '/icon.svg',
            '/mstile-70x70.png',
            '/mstile-144x144.png',
            '/mstile-150x150.png',
            '/mstile-310x150.png',
            '/mstile-310x310.png',
            '/android-chrome-36x36.png',
            '/android-chrome-48x48.png',
            '/android-chrome-72x72.png',
            '/android-chrome-96x96.png',
            '/android-chrome-144x144.png',
            '/android-chrome-192x192.png',
            '/android-chrome-256x256.png',
            '/android-chrome-384x384.png',
            '/android-chrome-512x512.png',
            '/safari-pinned-tab.svg',
            // 新增：更多可能的路径
            '/assets/favicon.ico',
            '/assets/images/favicon.ico',
            '/assets/img/favicon.ico',
            '/assets/icons/favicon.ico',
            '/img/favicon.ico',
            '/images/favicon.ico',
            '/static/favicon.ico',
            '/public/favicon.ico',
            '/resources/favicon.ico',
            '/media/favicon.ico',
            '/favicon/favicon.ico',
            '/icon/favicon.ico',
            '/favicons/favicon.ico',
            // PWA相关图标
            '/pwa-icon.png',
            '/pwa-icons/icon.png',
            '/assets/pwa/icon.png',
            // 添加更多尺寸变体
            '/favicon-48x48.png',
            '/favicon-64x64.png',
            '/favicon-120x120.png',
            '/favicon-128x128.png',
            '/favicon-144x144.png',
            '/favicon-150x150.png',
            '/favicon-152x152.png',
            '/favicon-180x180.png',
            '/favicon-256x256.png',
            '/favicon-512x512.png',
            // 增加微软特有格式的检查
            '/browserconfig.xml'
        ];
        
        // 4. 检查 HTML 中的 <meta> 标签中的图标引用
        const metaTags = document.querySelectorAll('meta[property="og:image"], meta[name="twitter:image"], meta[itemprop="image"]');
        metaTags.forEach(tag => {
            const content = tag.getAttribute('content');
            if (content) {
                try {
                    const iconUrl = new URL(content, window.location.origin).href;
                    addIconIfNotExists({
                        url: iconUrl,
                        type: tag.getAttribute('property') || tag.getAttribute('name') || tag.getAttribute('itemprop') || '未知',
                        size: '未知',
                        source: 'meta标签'
                    });
                } catch (e) {
                    // 忽略无效URL
                }
            }
        });
        
        // 检查可能的图标位置
        checkCommonIconLocations(commonIcons, rootUrl, statusElement);
        
        // 5. 网站主页上可能存在的图标
        const siteImages = document.querySelectorAll('img[alt*="logo"], img[src*="logo"], img[alt*="icon"], img[src*="icon"], img[class*="logo"], img[class*="icon"], img[id*="logo"], img[id*="icon"]');
        siteImages.forEach(img => {
            if (img.src) {
                addIconIfNotExists({
                    url: img.src,
                    type: 'website logo/icon',
                    size: `${img.naturalWidth}x${img.naturalHeight}`,
                    source: 'logo图片'
                });
            }
        });
        
        // 更新显示
        updateIconsDisplay();
        
        if (statusElement) statusElement.textContent = '图标搜索进行中...';
    }
    
    function checkCommonIconLocations(iconPaths, rootUrl, statusElement) {
        let checkedCount = 0;
        
        iconPaths.forEach(function(iconPath) {
            const iconUrl = rootUrl + iconPath;
            
            // 使用GM_xmlhttpRequest检查图标是否存在
            GM_xmlhttpRequest({
                method: 'HEAD',
                url: iconUrl,
                onload: function(response) {
                    checkedCount++;
                    if (response.status >= 200 && response.status < 400) {
                        // 图标存在
                        let type = '未知';
                        
                        // 增强版：更精确的Content-Type提取
                        const contentType = response.responseHeaders.match(/content-type:\s*([^;\r\n]+)/i);
                        if (contentType && contentType[1]) {
                            type = contentType[1].trim();
                        }
                        
                        addIconIfNotExists({
                            url: iconUrl,
                            type: '网站图标',
                            size: '未知',
                            source: '网站目录',
                            format: type
                        });
                        
                        // 增强版：如果是特定的内容类型，尝试获取更多信息
                        if (type.includes('xml') && iconPath.endsWith('browserconfig.xml')) {
                            // 尝试解析Microsoft browserconfig.xml获取更多图标
                            fetchMicrosoftIcons(iconUrl, rootUrl);
                        }
                        
                        updateIconsDisplay();
                    }
                    
                    if (checkedCount === iconPaths.length && statusElement) {
                        statusElement.textContent = '图标搜索完成';
                    }
                },
                onerror: function() {
                    checkedCount++;
                    if (checkedCount === iconPaths.length && statusElement) {
                        statusElement.textContent = '图标搜索完成';
                    }
                }
            });
            
            // 备用方法：直接尝试添加
            addIconIfNotExists({
                url: iconUrl,
                type: '可能的图标',
                size: '未知',
                source: '常见位置'
            });
        });
    }
    
    // 增强版：添加微软特有图标的获取功能
    function fetchMicrosoftIcons(configUrl, rootUrl) {
        GM_xmlhttpRequest({
            method: 'GET',
            url: configUrl,
            onload: function(response) {
                if (response.status >= 200 && response.status < 400) {
                    const parser = new DOMParser();
                    try {
                        const xmlDoc = parser.parseFromString(response.responseText, "text/xml");
                        const tileImages = xmlDoc.querySelectorAll('square70x70logo, square150x150logo, square310x310logo, wide310x150logo');
                        tileImages.forEach(img => {
                            const src = img.textContent || img.getAttribute('src');
                            if (src) {
                                let iconUrl = src;
                                if (!iconUrl.startsWith('http')) {
                                    iconUrl = new URL(iconUrl, rootUrl).href;
                                }
                                
                                addIconIfNotExists({
                                    url: iconUrl,
                                    type: 'Microsoft Tile',
                                    size: img.nodeName.replace('square', '').replace('wide', '').replace('logo', ''),
                                    source: 'browserconfig.xml'
                                });
                            }
                        });
                        updateIconsDisplay();
                    } catch (e) {
                        // 忽略解析错误
                    }
                }
            }
        });
    }
    
    function addIconIfNotExists(iconInfo) {
        // 检查是否已存在该URL的图标
        if (!icons.some(icon => icon.url === iconInfo.url)) {
            // 确定图标格式
            const url = iconInfo.url.toLowerCase();
            let format = 'other';
            
            // 增强版：支持更多格式
            if (url.endsWith('.ico')) format = 'ico';
            else if (url.endsWith('.png')) format = 'png';
            else if (url.endsWith('.jpg') || url.endsWith('.jpeg')) format = 'jpg';
            else if (url.endsWith('.svg')) format = 'svg';
            else if (url.endsWith('.webp')) format = 'webp';
            else if (url.endsWith('.gif')) format = 'gif';
            else if (url.endsWith('.bmp')) format = 'bmp';
            else if (url.endsWith('.avif')) format = 'avif';
            else if (url.endsWith('.tiff') || url.endsWith('.tif')) format = 'tiff';
            else if (url.endsWith('.heic')) format = 'heic';
            else if (url.endsWith('.heif')) format = 'heif';
            else if (url.endsWith('.jxr')) format = 'jxr';
            else if (url.endsWith('.jp2')) format = 'jp2';
            else if (url.endsWith('.apng')) format = 'apng';
            else if (url.endsWith('.jfif')) format = 'jfif';
            else if (url.startsWith('data:')) format = 'base64';
            else if (iconInfo.format) {
                // 增强版：针对Content-Type的检测也添加更多格式
                if (iconInfo.format.includes('png')) format = 'png';
                else if (iconInfo.format.includes('jpg') || iconInfo.format.includes('jpeg')) format = 'jpg';
                else if (iconInfo.format.includes('svg')) format = 'svg';
                else if (iconInfo.format.includes('webp')) format = 'webp';
                else if (iconInfo.format.includes('gif')) format = 'gif';
                else if (iconInfo.format.includes('bmp')) format = 'bmp';
                else if (iconInfo.format.includes('avif')) format = 'avif';
                else if (iconInfo.format.includes('tiff')) format = 'tiff';
                else if (iconInfo.format.includes('heic')) format = 'heic';
                else if (iconInfo.format.includes('ico')) format = 'ico';
                // 其他格式...
            }
            
            // 添加到图标列表
            icons.push({
                ...iconInfo,
                format: format
            });
        }
    }
    
    function updateIconsDisplay() {
        // 清除现有的图标显示（除了标题、关闭按钮、刷新按钮和过滤器）
        const existingItems = panel.querySelectorAll('.favicon-item');
        existingItems.forEach(item => item.remove());
        
        // 过滤图标列表
        const filteredIcons = icons.filter(icon => formatFilters[icon.format]);
        
        // 显示图标数量
        const statusText = panel.querySelector('.status-text');
        if (statusText) {
            statusText.textContent = `共找到 ${icons.length} 个图标，当前显示 ${filteredIcons.length} 个`;
        }
        
        if (filteredIcons.length > 0) {
            filteredIcons.forEach(function(icon) {
                const iconContainer = document.createElement('div');
                iconContainer.className = 'favicon-item';
                
                const img = document.createElement('img');
                img.src = icon.url;
                img.onerror = function() {
                    iconContainer.style.display = 'none';
                };
                
                const info = document.createElement('span');
                info.textContent = `类型: ${icon.type}, 尺寸: ${icon.size}`;
                info.style.color = '#ecf0f1'; // 增加：确保文字颜色鲜明
                info.style.display = 'block';
                info.style.margin = '5px 0';
                
                const sourceInfo = document.createElement('div');
                sourceInfo.style.fontSize = '11px';
                sourceInfo.style.color = '#bdc3c7'; // 修改：更改颜色以适应深色背景
                sourceInfo.style.padding = '3px';
                sourceInfo.style.backgroundColor = '#243342'; // 增加：添加背景色以增强可读性
                sourceInfo.style.borderRadius = '3px';
                sourceInfo.style.margin = '3px 0';
                sourceInfo.textContent = `来源: ${icon.source}, 格式: ${icon.format}`;
                
                const url = document.createElement('div');
                url.className = 'favicon-url';
                url.textContent = icon.url.length > 100 ? icon.url.substring(0, 97) + '...' : icon.url;
                url.title = icon.url; // 完整URL作为提示
                
                const actions = document.createElement('div');
                actions.className = 'favicon-actions';
                
                const copyButton = document.createElement('button');
                copyButton.textContent = '复制链接';
                copyButton.addEventListener('click', function() {
                    GM_setClipboard(icon.url);
                    copyButton.textContent = '已复制!';
                    setTimeout(function() {
                        copyButton.textContent = '复制链接';
                    }, 1000);
                });
                
                const openButton = document.createElement('button');
                openButton.textContent = '打开图标';
                openButton.addEventListener('click', function() {
                    // 特殊处理base64图标
                    if (icon.format === 'base64' || icon.url.startsWith('data:')) {
                        // 创建一个新的HTML文档，其中只包含这个图像
                        const newWindow = window.open('', '_blank');
                        if (newWindow) {
                            const imgType = icon.url.match(/^data:([^;,]+)/) ? icon.url.match(/^data:([^;,]+)/)[1] : 'image/png';
                            newWindow.document.write(`
                                <!DOCTYPE html>
                                <html>
                                <head>
                                    <title>Base64图标</title>
                                    <style>
                                        body {
                                            margin: 0;
                                            padding: 20px;
                                            display: flex;
                                            justify-content: center;
                                            align-items: center;
                                            min-height: 100vh;
                                            background-color: #f0f0f0;
                                            background-image: linear-gradient(45deg, #ddd 25%, transparent 25%),
                                                              linear-gradient(-45deg, #ddd 25%, transparent 25%),
                                                              linear-gradient(45deg, transparent 75%, #ddd 75%),
                                                              linear-gradient(-45deg, transparent 75%, #ddd 75%);
                                            background-size: 20px 20px;
                                            background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
                                        }
                                        img {
                                            max-width: 100%;
                                            max-height: 80vh;
                                            border: 1px solid #ccc;
                                            box-shadow: 0 0 10px rgba(0,0,0,0.1);
                                            background-color: white;
                                            padding: 10px;
                                        }
                                        .info {
                                            position: fixed;
                                            bottom: 10px;
                                            left: 0;
                                            right: 0;
                                            text-align: center;
                                            font-family: Arial, sans-serif;
                                            font-size: 12px;
                                            color: #666;
                                        }
                                    </style>
                                </head>
                                <body>
                                    <img src="${icon.url}" alt="Base64编码图标">
                                    <div class="info">图标类型: ${imgType}</div>
                                </body>
                                </html>
                            `);
                            newWindow.document.close();
                        } else {
                            alert('无法打开新窗口，可能被浏览器阻止了。请允许此网站打开弹出窗口。');
                        }
                    } else {
                        // 正常处理其他格式的图标
                        window.open(icon.url, '_blank');
                    }
                });
                
                const downloadButton = document.createElement('button');
                downloadButton.textContent = '下载';
                downloadButton.addEventListener('click', function() {
                    downloadIcon(icon.url);
                });
                
                actions.appendChild(copyButton);
                actions.appendChild(openButton);
                actions.appendChild(downloadButton);
                
                iconContainer.appendChild(img);
                iconContainer.appendChild(info);
                iconContainer.appendChild(sourceInfo);
                iconContainer.appendChild(url);
                iconContainer.appendChild(actions);
                
                panel.appendChild(iconContainer);
            });
        } else {
            const noIcons = document.createElement('div');
            noIcons.textContent = '没有找到图标';
            noIcons.style.color = '#ecf0f1'; // 增加：确保文字颜色鲜明
            noIcons.style.padding = '10px';
            noIcons.style.textAlign = 'center';
            panel.appendChild(noIcons);
        }
    }
    
    function downloadIcon(url) {
        // 从URL提取文件名
        let filename = url.split('/').pop() || 'favicon';
        
        // 处理URL中的查询参数
        if (filename.includes('?')) {
            filename = filename.split('?')[0];
        }
        
        // 增强版：处理数据URL
        if (url.startsWith('data:')) {
            const mimeMatch = url.match(/^data:([^;,]+)/);
            let extension = '.ico'; // 默认
            
            if (mimeMatch && mimeMatch[1]) {
                const mimeType = mimeMatch[1].toLowerCase();
                if (mimeType.includes('png')) extension = '.png';
                else if (mimeType.includes('jpeg') || mimeType.includes('jpg')) extension = '.jpg';
                else if (mimeType.includes('svg')) extension = '.svg';
                else if (mimeType.includes('webp')) extension = '.webp';
                else if (mimeType.includes('gif')) extension = '.gif';
                else if (mimeType.includes('ico')) extension = '.ico';
                // 添加更多MIME类型的检测
            }
            
            filename = 'favicon-base64' + extension;
        }
        
        // 确保文件有正确的扩展名
        const urlLower = url.toLowerCase();
        if (!filename.includes('.')) {
            // 增强版：支持更多格式
            if (urlLower.includes('.ico')) {
                filename += '.ico';
            } else if (urlLower.includes('.png')) {
                filename += '.png';
            } else if (urlLower.includes('.jpg') || urlLower.includes('.jpeg')) {
                filename += '.jpg';
            } else if (urlLower.includes('.svg')) {
                filename += '.svg';
            } else if (urlLower.includes('.webp')) {
                filename += '.webp';
            } else if (urlLower.includes('.gif')) {
                filename += '.gif';
            } else if (urlLower.includes('.bmp')) {
                filename += '.bmp';
            } else if (urlLower.includes('.avif')) {
                filename += '.avif';
            } else if (urlLower.includes('.tiff') || urlLower.includes('.tif')) {
                filename += '.tiff';
            } else if (urlLower.includes('.heic')) {
                filename += '.heic';
            } else if (urlLower.includes('.heif')) {
                filename += '.heif';
            } else if (urlLower.includes('.jxr')) {
                filename += '.jxr';
            } else if (urlLower.includes('.jp2')) {
                filename += '.jp2';
            } else if (urlLower.includes('.apng')) {
                filename += '.apng';
            } else if (urlLower.includes('.jfif')) {
                filename += '.jfif';
            } else {
                filename += '.ico'; // 默认扩展名
            }
        }
        
        // 使用GM_xmlhttpRequest下载图标为blob
        GM_xmlhttpRequest({
            method: 'GET',
            url: url,
            responseType: 'blob',
            onload: function(response) {
                // 创建blob URL
                const blob = response.response;
                const blobUrl = URL.createObjectURL(blob);
                
                // 创建下载链接
                const a = document.createElement('a');
                a.href = blobUrl;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                
                // 清理
                setTimeout(function() {
                    document.body.removeChild(a);
                    URL.revokeObjectURL(blobUrl);
                }, 100);
            },
            onerror: function() {
                // 如果GM_xmlhttpRequest失败，尝试直接下载
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                a.target = '_blank';
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        });
    }
})(); 